前一篇,我們順利的製作了一個 Terraform 模組。接下來要回到根模組建立組態檔來使用模組。
完整的範例檔案可以參考 Github 上的資料。
建立 main.tf
module
區塊載入模組source
填入自製模組的相對路徑bucket_name
provider "aws" {
region = "ap-northeast-1"
}
module "website_bucket" {
source = "./modules/static-s3-bucket"
bucket_name = "<YOUR BUCKET NAME>"
tags = {
Terraform = "true"
Environment = "dev"
}
}
建立 outputs.tf
output "website_bucket_arn" {
description = "ARN of the bucket"
value = module.website_bucket.arn
}
output "website_bucket_name" {
description = "Name (id) of the bucket"
value = module.website_bucket.name
}
output "website_endpoint" {
description = "Domain name of the bucket"
value = module.website_bucket.website_endpoint
}
現在的檔案清單
$ tree
.
├── main.tf
├── modules
│ └── static-s3-bucket
│ ├── README.md
│ ├── main.tf
│ ├── outputs.tf
│ └── variables.tf
├── outputs.tf
└── www
├── error.html
└── index.html
www
資料夾是我們另外準備要放到 s3 上測試用的網頁檔,你可以準備自己想要的檔案。
執行指令 terraform init
或 terraform get
安裝模組
$ terraform init
Initializing modules...
- website_bucket in modules/static-s3-bucket
Initializing the backend...
Initializing provider plugins...
- Finding latest version of hashicorp/aws...
- Using hashicorp/aws v3.7.0 from the shared cache directory
...
$ terraform apply
...
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
Outputs:
website_bucket_arn = arn:aws:s3:::terraform-practice-write-module
website_bucket_name = <YOUR BUCKET NAME>
website_endpoint = <YOUR BUCKET NAME>.s3-website-ap-northeast-1.amazonaws.com
s3 的儲存貯體 (bucket) 成功被建立了!
使用 aws cli 執行指令上傳檔案,把網頁檔上傳到剛剛建立好的儲存貯體 (bucket),可以用 terraform output website_bucket_name
指令找到儲存貯體名稱 (bucket name),再來組合 s3 cp 的指令
範例如下:
aws s3 cp www/ s3://$(terraform output website_bucket_name)/ --recursive
上傳成功後,就要打來網址來測試了
可以用 terraform output website_endpoint
指令找出網址。
網址大概會找這樣: https://<YOUR BUCKET NAME>.s3-us-west-2.amazonaws.com/index.html
打開網址,如果看到剛剛上傳的 index.html 就表示我們成功了!
測試結束了,我們要刪除測試資料。這次跟以往不太一樣,因為 s3 儲存貯體 (bucket) 要先清空才能刪掉。
假如沒有刪掉檔案就想執行 destroy
的話
$ terraform destroy
...
module.website_bucket.aws_s3_bucket.s3_bucket: Destroying... [id=terraform-practice-write-module]
Error: error deleting S3 Bucket (terraform-practice-write-module): BucketNotEmpty: The bucket you tried to delete is not empty
status code: 409, request id: XXXXXX, host id: 7eI2q66OaJxxxxxxxx
AWS 會給你一個 409 的錯誤!
所以我們要執行 aws s3 rm
刪掉檔案:
$ aws s3 rm s3://$(terraform output website_bucket_name)/ --recursive
再執行 terraform destroy
刪掉我們建立的基礎架構:
$ terraform destroy
...
module.website_bucket.aws_s3_bucket.s3_bucket: Destroying... [id=terraform-practice-write-module]
module.website_bucket.aws_s3_bucket.s3_bucket: Destruction complete after 1s
Destroy complete! Resources: 1 destroyed.